package com.yhj.servlet.container;

import java.io.PrintWriter;
import java.net.URL;
import java.net.URLClassLoader;

public class DynamicProcessor implements Processor {

	@Override
	public void process(ServletResponse response, ServletRequest request) {
		//取出uri    /servlet/servlet类名
		String uri=request.getUri();
		//取出servletname
		String servletName=uri.substring(uri.lastIndexOf("/")+1);
		//3.leijiazai ->仍要通过url地址来加载servlet字节码
		//	URLClassLoader
		URLClassLoader loader=null;
		
		//4.通过字节码反射成一个对象，
		Servlet servlet = null;
		try {
			URL url=new URL("file",null,TomcatConstants.BASE_PATH);
			URL [] urls=new URL[]{url};
			//创建了一个类加载器，这个加载器从项目下的webapps中读取servlet
			loader=new URLClassLoader(urls);
			//加servletname
			Class c=loader.loadClass(servletName);//因为是没有打包的java，类加载器默认加载的位置在bin下，所以可以加载到
			servlet = (Servlet)c.newInstance();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try{
			if(servlet!=null&&servlet instanceof Servlet){
				//控制生命周期=>init()=>service()
				servlet.init();
				servlet.service(response, request);
			}
		}catch(Exception e){
			String body=e.getMessage();
			body=gen500(body.getBytes().length)+body;
			PrintWriter out=response.getWriter();
			out.println(body);
			out.flush();
		}
	}
	
	private String gen500(int length) {
		String protocal404="HTTP/1.1 500 Server Internal ERROR\r\nContent-Type: text/html\r\nContent-Length: "+length+"\r\n\r\n";
		return protocal404;
	}

}
